package com.software.levelupandroid.home.ui.taskByPriority;

import android.content.Context;
import android.os.Looper;
import android.util.Log;

import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;

import com.software.levelupandroid.entity.Resource;
import com.software.levelupandroid.entity.Task;
import com.software.levelupandroid.home.CallBack;

import java.util.List;

/**
 * @Description TODO
 * @Author LiangYaJie
 * @CreateTime 2024年06月03日 14:23:17
 */
public class TaskByPriorityViewModel extends ViewModel {
    private final MutableLiveData<Resource<List<Task>>> taskListLiveData;
    public TaskByPriorityViewModel(){
        taskListLiveData = new MutableLiveData<>();
    }

    public LiveData<Resource<List<Task>>> getTaskListLiveData(){
        return taskListLiveData;
    }

    public void getTasksByPriority(Context context, String date, int priority){
        TaskByPriorityRepository.getTaskByPriorityRepository().getTaskByPriority(new CallBack<List<Task>>() {
            @Override
            public void onSuccess(List<Task> data) {
                runOnMainThread(taskListLiveData, Resource.success(data));

            }

            @Override
            public void onFailure(String msg) {
                Log.e("home:", msg);
                runOnMainThread(taskListLiveData, Resource.failure(msg, null));
            }
        }, context, date, priority);
    }

    /**
     * 将LiveData的赋值放在主线程上
     * @param taskListLiveData
     * @param data
     */
    private void runOnMainThread(MutableLiveData<Resource<List<Task>>> taskListLiveData, Resource<List<Task>> data) {
        if (Looper.myLooper() == Looper.getMainLooper())
            //当前线程在主线程
            taskListLiveData.setValue(data);
        else
            //当前线程不在主线程
            taskListLiveData.postValue(data);
    }

}
